<script setup>
import { ref, onMounted } from 'vue'
import { queryPageApi,addApi,updateApi,deleteApi,queryInfoApi,handleViolationApi} from '../../api/stu'
import { queryPageApi as queryAllClazzApi  } from '../../api/clazz' 
import { ElMessage,ElMessageBox } from 'element-plus'

onMounted(() => {
  queryAllClazz();
  search();
})


// 获取班级列表
const queryAllClazz = async () => {
  try {
    let result = await queryAllClazzApi('', '', '', 1, 10); // 补充默认分页参数
    if (result.code === 1 && result.data && result.data.rows) {
      clazzs.value = result.data.rows; // 使用 .rows 字段
    } else {
      console.warn('班级数据为空或请求失败:', result);
    }
  } catch (error) {
    console.error('获取班级数据出错:', error);
  }
}

//班级列表数据
let clazzs = ref([])

//搜索班级表单
let searchStu = ref({clazzId: '',degree: '',name: ''}) 

//学历列表数据
const degrees = ref([{ name: '初中', value: 1 },
                    { name: '高中', value: 2 },
                    { name: '大专', value: 3 },
                    { name: '本科', value: 4 },
                    { name: '硕士', value: 5 },
                    { name: '博士', value: 6 }
  ])

//学员列表数据
const stuList = ref([])


//性别列表数据
const genders = ref([{name:'男',value:1},{name:'女',value:2}])

//是否院校列表数据
const college = ref([{name:'是',value:1},{name:'否',value:0}])

//新增/修改表单
let student = ref({
   name: '',
  no: '',
  gender: '',
  phone: '',
  idCard: '',
  isCollege: '',
  address: '',
  degree: '',
  graduationDate: '',
  clazzId: ''
})

// 分页相关的数据模型
const currentPage = ref(1)  // 当前页码
const pageSize = ref(10)  // 每页显示条数
const background = ref(false) // 是否显示分页
const total = ref(0)  // 总记录数
//  分页大小改变的回调
const handleSizeChange = (val) => {
  console.log(`每页展示${val}条记录`)
  search();
}
//  当前页改变的回调
const handleCurrentChange = (val) => {
  console.log(`当前页码: ${val}`)
  search();
}

// 控制弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('新增员工')

//查询学员列表
const search = async () => { 
  console.log('当前查询参数:', searchStu.value);
  const result = await queryPageApi(
    searchStu.value.clazzId,
    searchStu.value.degree,
    searchStu.value.name,
    currentPage.value,
    pageSize.value
  );
  if(result.code){
    stuList.value = result.data.rows;
    total.value = result.data.total;

  }
}

//清空
const clear = () => {
  searchStu.value.name = '';
  searchStu.value.degree = '';
  searchStu.value.clazzId = '';
  search();
}

//新增学员
const addstu = () => {
  dialogTitle.value = '新增学员';
  dialogVisible.value = true;
  //重置表单的校验规则-提示信息
  if(stuFormRef.value){
   stuFormRef.value.resetFields(); 
  }
}

//表单引用
const stuFormRef = ref();

//表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  no: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger:  'blur' }
  ],
  gender:[{required:true,message:'请选择性别',trigger:'blur'}],
  phone:[
    {required:true,message:'请输入手机号',trigger:'blur'},
    {pattern:/^1[3-9]\d{9}$/,message:'请输入正确的手机号',trigger:'blur'}
  ],
  idCard:[{required:true,message:'请输入身份证号',trigger:'blur'},
    {pattern:/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,message:'请输入正确的身份证号',trigger:'blur'}
  ],
  isCollege:[{required:true,message:'请选择是否院校生',trigger:'blur'}],

})

//保存员工
const save = async () => {
  console.log('保存的员工信息:', student.value);
  if(!stuFormRef.value) return;
  stuFormRef.value.validate(async (valid) =>{
      if(valid){
        let result;
        if(student.value.id){
          //修改员工
           result = await updateApi(student.value);
        }else{
          //新增员工
           result = await addApi(student.value);
        }
          if(result.code){
              ElMessage.success('保存成功')
              search();
              dialogVisible.value = false;
          }else{
              ElMessage.error(result.msg);
          }
      }else{
          ElMessage.error('请填写正确的信息');
      }
  })
}

//修改编辑学员
const edit = async (id) => {
 const result = await queryInfoApi(id); 
 if(result.code){
  student.value = result.data;
  dialogTitle.value = '修改学员';
  dialogVisible.value = true;
 }
}

//根据id删除员工
const deleteById = (id) => {
  ElMessageBox.confirm('确定删除该学员吗？','提示',{
    confirmButtonText:'确定',
    cancelButtonText:'取消',
    type:'warning'
  }).then(async () => {
    const result = await deleteApi(id);
    if(result.code){
      ElMessage.success('删除成功')
      search();
    }else{
      ElMessage.error(result.msg);
    }
  }).catch(() =>{
    ElMessage.info('已取消删除');
  })
}

//经历勾选的员工的id
  const selectedIds = ref([]);

  //多选框勾选的回调
  const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map( item => item.id);
  }

//批量删除
const deleteByIds = () => {
  ElMessageBox.confirm('确定批量删除所选学员吗？','提示',{
    confirmButtonText:'确定',
    cancelButtonText:'取消',
    type:'warning'
}).then(async () => {
    if(selectedIds.value && selectedIds.value.length > 0){
      const result = await deleteApi(selectedIds.value);
      if(result.code){
        ElMessage.success('批量删除成功')
        search(); 
      }else{
        ElMessage.error(result.msg);
      }
    }else{
      ElMessage.error('请选择要删除的学员');
    }
}).catch(() =>{
  ElMessage.info('已取消批量删除'); 
})
}

//违纪扣分
const openViolation = (id) => { 
  ElMessageBox.prompt('请输入违纪扣分', '提示', {
   confirmButtonText: '确定',
   cancelButtonText: '取消',
   inputPattern:/\d?/,
   inputErrorMessage:'请输入正确的数字' 
  }).then(async(val) => {
    let result = await handleViolationApi(id,val.value);
    if(result.code){
      ElMessage.success('违纪处理成功')
      search(); 
    }else{
      ElMessage.error(result.msg);
    }
})
}



</script>

<template>

  <div>
      <div id="title">学员管理</div><br>
    </div>
  <!-- 搜索栏 -->
  <div class="container">
    <el-form :inline="true" :model="searchStu" class="demo-form-inline">
        <el-form-item label="学员姓名">
          <el-input v-model="searchStu.name" placeholder="请输入学员姓名" clearable />
        </el-form-item>

    <el-form-item label="最高学历">
        <el-select v-model="searchStu.degree" placeholder="请选择">
          <el-option v-for="degree in degrees" :label="degree.name" :value="degree.value" />
        </el-select>
    </el-form-item>

      <el-form-item label="所属班级">
        <el-select v-model="searchStu.clazzId" placeholder="请选择" style="width: 100%;">
          <el-option v-for="clazz in clazzs" :label="clazz.name" :value="clazz.id" /> 
        </el-select>
      </el-form-item>

      <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="info" @click="clear">清空</el-button>
        </el-form-item>
    </el-form>
  </div>

  <!-- 功能按钮 -->
  <div class="container">
      <el-button type="primary" @click="addstu">+ 添加学员</el-button>
      <el-button type="danger" @click="deleteByIds">- 批量删除</el-button>
  </div>

  <!-- 表格 -->
    <div class="container">
      <el-table :data="stuList" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="35" align="center"/>
        <el-table-column prop="name" label="姓名" width="80" align="center"/>
        <el-table-column prop="no" label="学号" width="130" align="center"/>
        <el-table-column prop="clazzName" label="班级" width="160" align="center"/>
        <el-table-column prop="gender" label="性别" width="70" align="center">
          <template #default="scope">
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="130" align="center"/>
        <el-table-column prop="degree" label="最高学历" width="90" align="center">
          <template #default="scope">
            <span v-if="scope.row.degree == 1">初中</span>
            <span v-else-if="scope.row.degree == 2">高中</span>
            <span v-else-if="scope.row.degree == 3">大专</span>
            <span v-else-if="scope.row.degree == 4">本科</span>
            <span v-else-if="scope.row.degree == 5">硕士</span>
            <span v-else-if="scope.row.degree == 6">博士</span>
            <span v-else>其他</span>
          </template>
        </el-table-column>
        <el-table-column prop="violationCount" label="违规次数" width="85" align="center"/>
        <el-table-column prop="violationScore" label="违纪扣分" width="85" align="center"/>
        <el-table-column prop="updateTime" label="最后操作时间" width="170" align="center"/>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="edit(scope.row.id)"><el-icon><EditPen /></el-icon>编辑</el-button>
            <el-button type="warning" size="small" @click="openViolation(scope.row.id)">违纪</el-button>
            <el-button type="danger" size="small" @click="deleteById(scope.row.id)"><el-icon><DeleteFilled /></el-icon>删除</el-button>
          </template>
        </el-table-column>
 />
      </el-table>
    </div>

    <!-- 分页条 -->
    <div class="container">
      <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10,20,30,50,75,100]"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    </div>

    <!-- 新增学员/修改学员 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="student" :rules="rules" ref="stuFormRef" label-width="80px">
        <!-- 基本信息 -->
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="student.name" placeholder="请输入学员姓名"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="学号" prop="no">
              <el-input v-model="student.no" placeholder="请输入学号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="student.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option v-for="g in genders" :key="g.value" :label="g.name" :value="g.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="student.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号">
              <el-input v-model="student.idCard" placeholder="请输入身份证号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否院校学员">
              <el-select v-model="student.isCollege" placeholder="请选择" style="width: 100%;">
                <el-option v-for="c in college" :key="c.value" :label="c.name" :value="c.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系地址">
              <el-input v-model="student.address" placeholder="请输入联系地址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最高学历" :label-width="labelWidth">
              <el-select v-model="student.degree" placeholder="请选择" style="width: 100%;">
                <el-option v-for="degree in degrees" :label="degree.name" :value="degree.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="毕业时间">
              <el-date-picker
                v-model="student.graduationDate"
                type="date"
                placeholder="请选择"
                :size="size"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
           <el-form-item label="所属班级" :label-width="labelWidth">
              <el-select v-model="student.clazzId" placeholder="请选择" style="width: 100%;">
                <el-option v-for="clazz in clazzs" :label="clazz.name" :value="clazz.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
  </el-dialog>   

<!-- 违纪处理 -->



</template>

<style scoped>

  .container{
    margin-top: 10px;
  }
  #title {
  font-size: 20px;
  font-weight: 600;
}
</style>